import moment from 'moment';
// import { MimeType, BosClient } from '@baiducloud/sdk';

function upload(file, res, type) {
  let time = moment().unix();
  let key = [type, time + file.name].join('/');
  let blob = file;
  let config = {
    credentials: {
      ak: res.accessKeyId,
      sk: res.secretKey
    },
    endpoint: 'https://su.bcebos.com',
    sessionToken: res.sessionToken
  };
  let client = new window.baidubce.sdk.BosClient(config);
  let ext = file.name.split(/\./g).pop();
  let mimeType = window.baidubce.sdk.MimeType.guess(ext);
  switch (type) {
    case 'img':
      if (/^image\//.test(mimeType)) {
        let options = {
          'Content-Type': mimeType,
          'mode': 'cors',
          'cache': 'no-cache'
        };

        let url = ["https:/", res.domain, key].join("/");
        client.putObjectFromBlob(res.bucket, key, blob, options);
        return url;
      }
      return;
    case 'application':
      if (/^application\//.test(mimeType)) {
        mimeType += '; charset=UTF-8';
        let options = {
          'Content-Type': mimeType,
          'mode': 'cors',
          'cache': 'no-cache'
        };

        let url = ["https:/", res.domain, key].join("/");
        client.putObjectFromBlob(res.bucket, key, blob, options);
        return url;
      }
      return;
    case 'any':
        if (/^application\//.test(mimeType) || /^image\//.test(mimeType)) {
          mimeType += '; charset=UTF-8';
          let options = {
            'Content-Type': mimeType,
            'mode': 'cors',
            'cache': 'no-cache'
          };
  
          let url = ["https:/", res.domain, key].join("/");
          client.putObjectFromBlob(res.bucket, key, blob, options);
          return url;
        }
      return;
    case 'text':
      if (/^text\//.test(mimeType)) {

        mimeType += '; charset=UTF-8';
      }
      let options = {
        'Content-Type': mimeType,
        'mode': 'cors',
        'cache': 'no-cache'
      };

      let url = ["https:/", res.domain, key].join("/");
      client.putObjectFromBlob(res.bucket, key, blob, options);
      return url;
    default:
      return;
  }
}


export function uploadImg(file, res) {
  return upload(file, res, 'img');
}

export function uploadApp(file, res) {
  return upload(file, res, 'application');
}

export function uploadAny(file, res) {
  return upload(file, res, 'any');
}